package com.znyj.servlet.interceptor;

import com.znyj.servlet.utilsTool.CommonTool;
import com.znyj.servlet.utilsTool.Helper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.regex.Pattern;


/**
 * Created by gaoliwei02 on 17/7/5.
 */
public class LoginInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);

    public static final String URL_REGEX = "^/(crypt|sign|factory|system)/.*$";
    public static final String TEST_REGEX = "^/(demo|test)/.*$";
    private static Pattern pattern;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String action = request.getRequestURI().substring(request.getContextPath().length());


        //包含png、jpg等资源请求放行
        if (Helper.matchExclude(action)) {return true;}

        //对外接口或者测试接口放行
        pattern = Pattern.compile(URL_REGEX);
        if (pattern.matcher(action).matches()) {return true;}

        //测试接口
        pattern = Pattern.compile(TEST_REGEX);
        if (pattern.matcher(action).matches()) {return true;}

//        //只允许内部IP调用inner接口
//        if ((action.indexOf(".inner") != -1)) {
//            if (request.getRemoteAddr().equals("0:0:0:0:0:0:0:1")) {
//                return true;
//            } else {
//                return false;
//            }
//        }

        //开始权限分级
        HttpSession session = request.getSession();
        String username = (String) session.getAttribute("username");
        Integer rolePermission = (Integer) session.getAttribute("rolePermission");

        long diff = session.getMaxInactiveInterval() * 1000;
        long create = (System.currentTimeMillis() - session.getCreationTime());
        if (create > diff) {
            session.invalidate();
            request.getRequestDispatcher("/WEB-INF/views/page/sign_page.jsp").forward(request, response);
            return false;
        }

        //如果已经登录放行
        if (username != null) {
            boolean authority = CommonTool.permissionCheck(rolePermission, action);
            if (authority) {
                return true;
            } else {
                request.getRequestDispatcher("/WEB-INF/views/no_access.jsp").forward(request, response);
                return false;
            }
        } else {
            request.getRequestDispatcher("/WEB-INF/views/page/sign_page.jsp").forward(request, response);
            return false;
        }

//
//        ||(action.indexOf("user.") == 1
//        if (Helper.matchExclude(action))){
//            //包含png、jpg等资源请求放行
//            return true;
//        }else{
//            HttpSession session = request.getSession();
//
//            String cryptMsg = (String) session.getAttribute("cryptMsg");
//            JSONObject json = JSON.parseObject(DesUtil.decrypt(cryptMsg));
//            String username = json.getString("username");
//            Integer rolePermission = json.getInteger("rolePermission");
//
//            //如果cookie超时取消
//            long diff = session.getMaxInactiveInterval() * 1000;
//            long create = (System.currentTimeMillis() - session.getCreationTime());
//            if (create > diff) {
//                session.invalidate();
//                request.getRequestDispatcher("/WEB-INF/views/sign_page.jsp").forward(request, response);
//                return false;
//            }
//
//            if (username != null) {
//                //如果已经登录放行
//                //权限控制 rolePermission,action
//                boolean authority = CommonTool.permissionCheck(rolePermission, action);
//                if (authority) {
//                    return true;
//                } else {
//                    request.getRequestDispatcher("/WEB-INF/views/no_access.jsp").forward(request, response);
//                    return false;
//                }
//            } else {
//                //所有其他请求进入login
//                request.getRequestDispatcher("/WEB-INF/views/sign_page.jsp").forward(request, response);
//                return false;
//            }
//        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
